package com.kuangjia.student_ems.controller;

import com.kuangjia.student_ems.dto.DepartmentDTO;
import com.kuangjia.student_ems.dto.request.DepartmentRequest;
import com.kuangjia.student_ems.service.DepartmentService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@RestController
@RequestMapping("/departments")
public class DepartmentController {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private DepartmentService departmentService;

    @GetMapping
    public ResponseEntity<List<DepartmentDTO>> getAllDepartments() {
        try {
            return ResponseEntity.ok(departmentService.getAllDepartments());
        } catch (Exception e) {
            logger.error("获取所有部门时发生异常", e);
            throw e;
        }
    }

    @GetMapping("/search")
    public ResponseEntity<List<DepartmentDTO>> searchDepartments(@RequestParam String keyword) {
        try {
            return ResponseEntity.ok(departmentService.searchDepartments(keyword));
        } catch (Exception e) {
            logger.error("搜索部门时发生异常，关键词: {}", keyword, e);
            throw e;
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<DepartmentDTO> getDepartmentById(@PathVariable Long id) {
        try {
            return ResponseEntity.ok(departmentService.getDepartmentById(id));
        } catch (Exception e) {
            logger.error("根据ID获取部门时发生异常，部门ID: {}", id, e);
            throw e;
        }
    }

    @PostMapping
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<DepartmentDTO> createDepartment(@Valid @RequestBody DepartmentRequest departmentRequest) {
        try {
            return new ResponseEntity<>(departmentService.createDepartment(departmentRequest), HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error("创建部门时发生异常，部门名称: {}", departmentRequest.getName(), e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<DepartmentDTO> updateDepartment(@PathVariable Long id, @Valid @RequestBody DepartmentRequest departmentRequest) {
        try {
            return ResponseEntity.ok(departmentService.updateDepartment(id, departmentRequest));
        } catch (Exception e) {
            logger.error("更新部门时发生异常，部门ID: {}, 部门名称: {}", id, departmentRequest.getName(), e);
            throw e;
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<Void> deleteDepartment(@PathVariable Long id) {
        try {
            departmentService.deleteDepartment(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            logger.error("删除部门时发生异常，部门ID: {}", id, e);
            throw e;
        }
    }

    @GetMapping("/page")
    public IPage<DepartmentDTO> getDepartmentPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            if (pageNum < 1) pageNum = 1;
            if (pageSize < 1) pageSize = 10;
            Page<com.kuangjia.student_ems.entity.Department> page = new Page<>(pageNum, pageSize);
            return departmentService.getDepartmentPage(page, keyword);
        } catch (Exception e) {
            logger.error("分页查询部门时发生异常，页码: {}, 页大小: {}, 关键词: {}", pageNum, pageSize, keyword, e);
            Page<DepartmentDTO> emptyPage = new Page<>();
            emptyPage.setRecords(java.util.Collections.emptyList());
            emptyPage.setTotal(0);
            return emptyPage;
        }
    }
} 